package com.yj.suncity.user;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.user.bean.LoginBean;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.Utils;
import com.yj.suncity.utis.DialogUtils.ItemCall;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity implements OnClickListener {
	private static final int TIMER = 101;
	private Context context;
	private Button mBtn_verification_code;
	private EditText mEdt_phone, mEdt_pwd, mEdt_verification_code;
	private String verification_code = "";
	private List<NameValuePair> pairs;
	private SharedPreferencesUtil preferencesUtil;
	private Timer mTimer;
	private int mTime = 60;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TIMER:
				if (mTime <= 0) {
					mTimer.cancel();
					mTimer = null;
					// task.cancel();
					// task=null;
					mTime = 60;
					btnIsValid();
				} else {
					btnIsUnvalid(mTime + "秒后重新获取");
				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		context = this;
		pairs = new ArrayList<NameValuePair>();
		preferencesUtil = SharedPreferencesUtil.getInstance();
		findView();
	}

	private void findView() {
		findViewById(R.id.btnHeadBack).setOnClickListener(this);
		findViewById(R.id.btn_regist).setOnClickListener(this);
		findViewById(R.id.btn_login).setOnClickListener(this);
		mBtn_verification_code = (Button) findViewById(R.id.btn_verifica_code);
		mBtn_verification_code.setOnClickListener(this);
		mEdt_phone = (EditText) findViewById(R.id.edt_user_phone);
		mEdt_pwd = (EditText) findViewById(R.id.edt_user_pwd);
		mEdt_phone.setText(preferencesUtil.getString(context,
				ShareCon.USERFILE, ShareCon.USERPHONE, ""));
		mEdt_verification_code = (EditText) findViewById(R.id.edt_verification_code);
	}

	private void sendVerification(String phone) {
		String path = URLCon.短信接口 + "?action=sendsecuritycode&typeid=2&mobile="
				+ phone;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "正在发送验证码......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							verification_code = jsonObject.optString("code");

							ToastUtil.ShowToast(context, "发送成功~~~");
							btnIsUnvalid("60秒后重新获取");
							mTimer = new Timer();
							mTimer.schedule(new TimerTask() {
								@Override
								public void run() {
									mTime--;
									Message message = new Message();
									message.what = TIMER;
									handler.sendMessage(message);
								}
							}, 1000, 1000);
						} else {
							btnIsValid();
							ToastUtil.ShowToast(context, "发送失败！");
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	// 获取验证码按钮有效
	private void btnIsValid() {
		mBtn_verification_code.setClickable(true);
		mBtn_verification_code.setEnabled(true);
		mBtn_verification_code.setText("获取验证码");
		mBtn_verification_code.setTextColor(getResources().getColor(
				R.color.orange));
	}

	// 获取验证码按钮无效
	private void btnIsUnvalid(String btnText) {
		mBtn_verification_code.setClickable(false);
		mBtn_verification_code.setEnabled(false);
		mBtn_verification_code.setText(btnText);
		mBtn_verification_code.setTextColor(getResources().getColor(
				R.color.txt_gray_light));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.btn_faget_pwd:
			Intent intent=new Intent(context, UpdatePwdActivity1.class);
			intent.putExtra("titlename", "忘记密码");
			intent.putExtra("flag", 2);
			startActivity(intent);
			break;
		case R.id.btn_regist:
			popView();
			// startActivity(new Intent(this, RegistActivity.class));
			break;
		case R.id.btn_verifica_code:
			String phone = mEdt_phone.getText().toString().trim();
			if (phone.equals("")) {
				ToastUtil.ShowToast(context, "请输入手机号码！");
				return;
			}
			if (!Utils.checkMobilePhone(phone)) {
				ToastUtil.ShowToast(context, "手机号码不正确！");
				return;
			}
			sendVerification(phone);
			break;
		case R.id.btn_login:
			String phone1 = mEdt_phone.getText().toString().trim();
			String ver_code = mEdt_verification_code.getText().toString()
					.trim();
			String pwd = mEdt_pwd.getText().toString().trim();
			if (phone1.equals("")) {
				ToastUtil.ShowToast(context, "请输入手机号码！");
				return;
			}
			if (!Utils.checkMobilePhone(phone1)) {
				ToastUtil.ShowToast(context, "手机号码不正确！");
				return;
			}
			if (pwd.equals("")) {
				ToastUtil.ShowToast(context, "请输入密码！");
				return;
			}

			// 验证码
			// if (ver_code.equals("")) {
			// ToastUtil.ShowToast(context, "请输入验证码！");
			// return;
			// }
			// if (!ver_code.equals(verification_code)) {
			// ToastUtil.ShowToast(context, "验证码不正确！");
			// return;
			// }
			login(phone1, pwd);
			break;
		}
	}

	private void login(String phone, String pwd) {
		pairs.clear();
		String path = URLCon.用户;
		pairs.add(new BasicNameValuePair("action", "login"));
		pairs.add(new BasicNameValuePair("mobile", phone));
		pairs.add(new BasicNameValuePair("password", pwd));
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, pairs, null,
				false, null, true, "正在登录......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						LoginBean loginBean = new LoginBean(jsonObject);
						if (loginBean.getSuccess().equals("1")) {
							preferencesUtil.putBoolean(context,
									ShareCon.USERFILE, ShareCon.ISLOGIN, true);
							preferencesUtil.putString(context,
									ShareCon.USERFILE, ShareCon.USERID,
									loginBean.getId());
							preferencesUtil.putString(context,
									ShareCon.USERFILE, ShareCon.USERNAME,
									loginBean.getUsername());
							preferencesUtil.putString(context,
									ShareCon.USERFILE, ShareCon.USERPHONE,
									loginBean.getTelphone());

							preferencesUtil.putString(context,
									ShareCon.USERFILE, ShareCon.USERINTEGRAL,
									loginBean.getPositionid());
							if (loginBean.getUser_type().equals("2")) {// 商户
								preferencesUtil.putBoolean(context,
										ShareCon.USERFILE, ShareCon.USERTYPE,
										true);
								preferencesUtil.putString(context,
										ShareCon.USERFILE, ShareCon.SHOPID,
										loginBean.getEntid());
								preferencesUtil.putString(context,
										ShareCon.USERFILE, ShareCon.USERLOGO,
										"");
							} else {
								preferencesUtil.putBoolean(context,
										ShareCon.USERFILE, ShareCon.USERTYPE,
										false);
								preferencesUtil.putString(context,
										ShareCon.USERFILE, ShareCon.USERLOGO,
										loginBean.getHead_photo());
							}

							LoginActivity.this.finish();
						} else {
							ToastUtil.ShowToast(context, loginBean.getMsg());
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void popView() {
		DialogUtils dialogUtils = DialogUtils.getInstance();
		dialogUtils.RegistDialog(context, new ItemCall() {
			@Override
			public void onIndexCall(int index) {
				if (index == 1) {// 个人注册
				} else if (index == 2) {// 商户注册
				}
				Intent intent = new Intent(context, RegistActivity.class);
				intent.putExtra("usertype", index);
				startActivityForResult(intent, 1);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1 && resultCode == 1) {
			this.finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}
